package com.accessibleworlds.user;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.accessibleworlds.R;
import com.accessibleworlds.report.CreateReport;
import com.accessibleworlds.report.EditOldReports;
import com.accessibleworlds.report.SearchReport;
import com.accessibleworlds.util.Connections;
import com.accessibleworlds.util.SharedVariables;

public class UserPage extends Activity implements OnClickListener{

	private String previousID, userID, topic, message;

	private Button editInfo,report,mesAdmin,logout;

	private boolean isInvisible;
	
	private Dialog alertDialog;

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userpage);

		SharedPreferences getPreferences = getSharedPreferences(SharedVariables.fileName, MODE_PRIVATE);
		userID = getPreferences.getString("userID", "");
		
		Bundle bundle = getIntent().getExtras();
		previousID = bundle.getString("previousID");
		isInvisible = bundle.getBoolean("isInvisible");

		if(previousID.equalsIgnoreCase(SharedVariables.mainID) || previousID.equalsIgnoreCase(SharedVariables.loginID)) {

		}

		initializeVariables();
		changeLanguage();
		
		if(isInvisible) {
        	moveTaskToBack(true);
        }
	}

	@Override
	protected void onResume() {
		super.onResume();
		isInvisible=false;
		changeLanguage();
	}

	@Override
	protected void onPause() {
		super.onPause();
		isInvisible = true;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			moveTaskToBack(true);
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
	
	private void initializeVariables() {
		editInfo = (Button)findViewById(R.id.userPageEditInfo);
		report = (Button)findViewById(R.id.userPageReport);
		mesAdmin = (Button)findViewById(R.id.userPagemesAdmin);
		logout = (Button)findViewById(R.id.userPageLogout);

		editInfo.setOnClickListener(this);
		report.setOnClickListener(this);
		mesAdmin.setOnClickListener(this);
		logout.setOnClickListener(this);
		progressDialog = new ProgressDialog(UserPage.this);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
	}

	private void changeLanguage() {
		editInfo.setText(getResources().getStringArray(R.array.editInformations)[SharedVariables.currentLanguage]);
		report.setText(getResources().getStringArray(R.array.reports)[SharedVariables.currentLanguage]);
		mesAdmin.setText(getResources().getStringArray(R.array.mesAdmin)[SharedVariables.currentLanguage]);
		logout.setText(getResources().getStringArray(R.array.logout)[SharedVariables.currentLanguage]);
	}

	public void onClick(View v) {
		if(v.getId()==editInfo.getId()) {
			//Create a dialog pop up window with 3 buttons
			alertDialog = new Dialog(this);
			alertDialog.setContentView(R.layout.pop_up_with_two_button);
			alertDialog.setTitle("Edit Information");
			Button editPersonal = (Button) alertDialog.findViewById(R.id.twobuttons_choice1);
			editPersonal.setText("Edit Personal Information");
			Button editOldReport = (Button) alertDialog.findViewById(R.id.twobuttons_choice2);
			editOldReport.setText("Edit Old Reports");
			alertDialog.show();
			
			editPersonal.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(UserPage.this,EditPersonalInformation.class);
					Bundle bundle = new Bundle();
					bundle.putString("previousID", SharedVariables.userPageID);
					intent.putExtras(bundle);
					startActivity(intent);
					overridePendingTransition(R.anim.fade, R.anim.hold);
					alertDialog.dismiss();
					finish();
				}
			});

			editOldReport.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(UserPage.this,EditOldReports.class);
					Bundle bundle = new Bundle();
					bundle.putString("previousID", SharedVariables.userPageID);
					intent.putExtras(bundle);
					startActivity(intent);
					overridePendingTransition(R.anim.fade, R.anim.hold);
					alertDialog.dismiss();
					finish();
				}
			});
		}
		else if(v.getId()==report.getId()) {
			
			alertDialog = new Dialog(this);
			alertDialog.setContentView(R.layout.pop_up_with_two_button);
			alertDialog.setTitle("Reports");
			Button createReport = (Button) alertDialog.findViewById(R.id.twobuttons_choice1);
			createReport.setText("Create Report");
			Button searchReport = (Button) alertDialog.findViewById(R.id.twobuttons_choice2);
			searchReport.setText("Search Report");
			alertDialog.show();
			
			createReport.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(UserPage.this,CreateReport.class);
					Bundle bundle = new Bundle();
					bundle.putString("previousID", SharedVariables.userPageID);
					intent.putExtras(bundle);
					startActivity(intent);
					overridePendingTransition(R.anim.fade, R.anim.hold);
					alertDialog.dismiss();
					finish();
				}
			});
			
			searchReport.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(UserPage.this,SearchReport.class);
					Bundle bundle = new Bundle();
					bundle.putString("previousID", SharedVariables.userPageID);
					intent.putExtras(bundle);
					startActivity(intent);
					overridePendingTransition(R.anim.fade, R.anim.hold);
					alertDialog.dismiss();
					finish();
				}
			});
			
		}
		else if(v.getId()==mesAdmin.getId()) {
			alertDialog = new Dialog(this);
			alertDialog.setContentView(R.layout.message_to_admin);
			alertDialog.setTitle("Send Message to Admin");
			final EditText Topic = (EditText) alertDialog.findViewById(R.id.mesToAdminTopic);
			final EditText Message = (EditText) alertDialog.findViewById(R.id.mesToAdminMessage);
			Button sendMessage = (Button) alertDialog.findViewById(R.id.mesToAdminButton);
			sendMessage.setText("Send");
			alertDialog.show();
			sendMessage.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					topic = Topic.getText().toString();
					message = Message.getText().toString();
					System.out.println("Admin mes : "+topic+" "+message);
					new sendMesToAdmin().execute();
				}
			});
			
		}
		else if(v.getId()==logout.getId()) {
			Intent intent = new Intent(UserPage.this,StartPage.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.userPageID);
			intent.putExtras(bundle);
			
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
			SharedPreferences.Editor editor = preferences.edit();
			editor.putBoolean("autoLogin", false);
			editor.putString("email", "");
			editor.putString("password", "");
			editor.putBoolean("blindUserMode", false);
			editor.commit();
			
			SharedPreferences savePreferences = getSharedPreferences(SharedVariables.fileName, MODE_PRIVATE);
			SharedPreferences.Editor saveEditor = savePreferences.edit();
			saveEditor.putString("userID", "");
			saveEditor.putString("email", "");
			saveEditor.putString("password", "");
			saveEditor.putString("lastName", "");
			saveEditor.putString("firstName", "");
			saveEditor.putString("birthday", "");
			saveEditor.commit();

			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
		}
	}

	public class sendMesToAdmin extends AsyncTask<Void, Integer, Boolean>{

		private String[] takenData = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {

			if(Connections.serviceStatus()) {

				try {
					String url = Connections.URI+Connections.sendMessageToAdmin;
					String [] parameters = {"accessCode","userID","topic","message"};
					String[] paramaterValues = {SharedVariables.accessCode, userID, topic, message};
					System.out.println("Send database "+ userID+" "+topic+" "+message);
					takenData = Connections.connection(url,parameters,paramaterValues);
					if("OK".equalsIgnoreCase(takenData[0])) {
						publishProgress(1);
						return true;
					}
					else {
						publishProgress(2);
						return false;
					}
				}
				catch (Exception ex) {
					publishProgress(2);
				}
			}
			else {
				publishProgress(0);
			}
			return false;
		}

		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				AlertDialog alertDialog = new AlertDialog.Builder(UserPage.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.connectionProblemException)[SharedVariables.currentLanguage]);
				alertDialog.setButton(getResources().getStringArray(R.array.tryAgain)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						new sendMesToAdmin().execute();
					}
				});
				alertDialog.setButton2(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
				alertDialog.show();
			}
			progressDialog.dismiss();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			String res;
			if(result)
				res = "Your message has been sent to Admin";
			else
				res = "There is a problem with the connection please try again later";
			alertDialog.dismiss();
			Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
		}
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mainMenu = getMenuInflater();
		mainMenu.inflate(R.menu.mainmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem((R.id.menuOptions)).setTitle(getResources().getStringArray(R.array.options)[SharedVariables.currentLanguage]);
		menu.findItem(R.id.menuOptions).setIcon(R.drawable.optionsicon);
		menu.findItem((R.id.menuExit)).setTitle(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage]);
		menu.findItem((R.id.menuExit)).setIcon(R.drawable.exiticon);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==R.id.menuOptions) {
			Intent intent = new Intent(UserPage.this,Options.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.userPageID);
			intent.putExtras(bundle);
			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
		}
		else if (item.getItemId()==R.id.menuExit) {
			finish();
		}
		return super.onOptionsItemSelected(item);
	}
}
